package com.moyo.repository;

import com.moyo.model.SysPermission;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 权限数据访问（内存实现，后续可替换为JPA/MyBatis）
 */
public class SysPermissionRepository {
    private final Map<Long, SysPermission> permissionMap = new HashMap<>();
    private final AtomicLong idGen = new AtomicLong(1);

    public SysPermission save(SysPermission permission) {
        if (permission.getId() == null) {
            permission.setId(idGen.getAndIncrement());
        }
        permissionMap.put(permission.getId(), permission);
        return permission;
    }

    public Optional<SysPermission> findById(Long id) {
        return Optional.ofNullable(permissionMap.get(id));
    }

    public Optional<SysPermission> findByCode(String code) {
        return permissionMap.values().stream()
                .filter(p -> p.getCode().equals(code))
                .findFirst();
    }

    public List<SysPermission> findByParentId(Long parentId) {
        return permissionMap.values().stream()
                .filter(p -> Objects.equals(p.getParentId(), parentId))
                .sorted(Comparator.comparing(SysPermission::getSort))
                .toList();
    }

    public List<SysPermission> findAll() {
        return new ArrayList<>(permissionMap.values());
    }

    public void deleteById(Long id) {
        permissionMap.remove(id);
    }
} 